package com.example.springbootserve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springbootserve.controller.Request.BaseRquest;
import com.example.springbootserve.controller.Request.LoginRequest;
import com.example.springbootserve.controller.Request.PasswordRequest;
import com.example.springbootserve.controller.dto.LoginDTO;
import com.example.springbootserve.entity.Admin;
import com.example.springbootserve.exception.ServiceException;
import com.example.springbootserve.mapper.AdminMapper;
import com.example.springbootserve.service.IAdminService;
import com.example.springbootserve.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class AdminService implements IAdminService {

    @Autowired
    AdminMapper adminMapper;

    private static final String DEFAULT_PASSWORD = "123";
    private static final String PASS_SAULT = "system";

    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    @Override
    public PageInfo<Admin> page(BaseRquest baseRquest) {
        PageHelper.startPage(baseRquest.getPageNum(), baseRquest.getPageSize());
        List<Admin> users = adminMapper.listByCondition(baseRquest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(Admin obj) {
        //默认密码
        if (StrUtil.isBlankIfStr(obj.getPassword())) {
            obj.setPassword(DEFAULT_PASSWORD);
        }
        obj.setPassword(securePass(obj.getPassword()));        //密码加盐
        try {
            adminMapper.save(obj);
        } catch (DuplicateKeyException e) {
            log.error("数据插入失败，username{}", obj.getUsername());
            throw new ServiceException("用户插入重复");

        }
    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }

    @Override
    public void update(Admin obj) {
        obj.setUpdatetime(new Date());
        adminMapper.updateById(obj);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public LoginDTO login(LoginRequest request) {
        Admin admin = null;
        try {
            admin = adminMapper.getByUsername(request.getUsername());
        } catch (Exception e) {
            log.error("根据用户名{} 查询出错",request.getUsername());
            throw new ServiceException("用户名错误");
        }
        if (admin == null) {
            throw new ServiceException("用户名或密码错误");
        }
        //判断密码是否合法
        String securePass = securePass(request.getPassword());
        if (!securePass.equals(admin.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        if (!admin.isStatus()) {
            throw new ServiceException("当前的用户已被禁用，请联系管理员");
        }
        LoginDTO loginDTO = new LoginDTO();
        BeanUtil.copyProperties(admin, loginDTO);

        //生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()),admin.getPassword());
        loginDTO.setToken(token);
        return loginDTO;
    }

    @Override
    public void changePass(PasswordRequest request) {
        //需要对新的密码进行加密
        request.setNewPass(securePass(request.getNewPass()));

        int count = adminMapper.updatePassword(request);
        if (count <= 0) {
            throw new ServiceException("用户名或密码错误");
        }
    }

    private String securePass(String password) {
        return SecureUtil.md5(password + PASS_SAULT);
    }
}
